import { useEffect, useMemo } from 'react'
import { Outlet, useLocation } from 'react-router'
import { useMemoizedFn } from 'ahooks'
import { Button, message, Segmented, Space } from 'antd'
import { StatusPanelDef } from '@ag-grid-community/core'

import { CusAgGrid, ICusAgGridProps } from '@/components/CusAgGrid'
import { UnifiedPagination } from '@/components/UnifiedPagination'
import { InpTransferOrderNumModal } from '../components/InpTransferOrderNumModal'
import { UploadPODFilesModal } from '../components/UploadWaybillFiles'
import { getLogisticsStatusName } from '../utils'
import { aptPostCreateShippingOrders } from './apis'
import { FilterOMS } from './FilterOMS'
import { FilterTMS } from './FilterTMS'
import { IOrderListItem } from './interface'
import { useBoundStore } from './store'
import { useColDefs, useOnColumnGroupOpened, useOnColumnVisible, useSideBar } from './useColConfig'
import { useOrderList } from './useOrderList'
import { popupSlot } from './utils'
import styles from './styles.module.less'

export const List = () => {
  const { pathname } = useLocation()
  if (pathname.startsWith('/biz/trackOrder/list/detail')) return <Outlet /> // 有详情页
  return <ListInner />
}

function ListInner() {
  useOrderList() // 放最顶部

  const gridRef = useBoundStore(v => v.gridRef)
  const loading = useBoundStore(v => v.request?.loading)
  const data = useBoundStore(v => v.request?.data)
  const page = useBoundStore(v => v.reqData.page)
  const size = useBoundStore(v => v.reqData.size)
  const logisticsStatus = useBoundStore(v => v.reqData.logisticsStatus)
  const selectedLen = useBoundStore(v => v.selectedKeys.length)
  const setSelectedKeys = useBoundStore(v => v.setSelectedKeys)
  const setSelectWaybillNos = useBoundStore(v => v.setSelectWaybillNos)
  const selectWaybillNos = useBoundStore(v => v.selectWaybillNos)
  const setReqData = useBoundStore(v => v.setReqData)
  const getData = useBoundStore(v => v.getData)

  const { defaultColDef, columnDefs } = useColDefs()
  const sideBar = useSideBar()
  const onColumnVisible = useOnColumnVisible()
  const onColumnGroupOpened = useOnColumnGroupOpened()

  // 勾选统计 & 分页器
  const statusBar = useMemo<ICusAgGridProps['statusBar']>(() => {
    const statusPanels: StatusPanelDef[] = []
    if ($APP === 'TMS') {
      statusPanels.push({
        statusPanel: () => (
          <div className={styles.statusBar_left}>
            已选中<b>{selectedLen}</b>条
          </div>
        ),
        align: 'left',
      })
    }
    statusPanels.push({
      statusPanel: UnifiedPagination,
      statusPanelParams: UnifiedPagination.defineProps({
        current: page,
        pageSize: size,
        total: data?.total,
        onChange: (page, size) => {
          setReqData({ page, size })
          getData(true)
        },
      }),
    })
    return { statusPanels }
  }, [data?.total, getData, page, selectedLen, setReqData, size])

  // 行勾选
  const rowSelection = useMemo<ICusAgGridProps<IOrderListItem>['rowSelection']>(() => {
    if ($APP === 'OMS') return undefined
    return { mode: 'multiRow' }
  }, [])
  const onRowSelected = useMemoizedFn<NonNullable<ICusAgGridProps<IOrderListItem>['onRowSelected']>>(() => {
    if ($APP === 'OMS') return
    const rows = gridRef.current?.api.getSelectedRows()
    if (rows) {
      setSelectedKeys(rows.map(r => r.recordId))
      setSelectWaybillNos(rows.map(r => r.waybillNo))
    }
  })

  // 固定行勾选列
  const onGridReady = useMemoizedFn<NonNullable<ICusAgGridProps<IOrderListItem>['onGridReady']>>(({ api }) => {
    if ($APP === 'OMS') return
    api.setColumnsPinned(['ag-Grid-ControlsColumn'], 'left')
  })

  // 清理，保留筛选条件
  useEffect(
    () => () =>
      useBoundStore.setState({ ...useBoundStore.getInitialState(), reqData: useBoundStore.getState().reqData }, true),
    [],
  )

  return (
    <div className={styles.box}>
      <div className={styles.filter}>{$APP === 'TMS' ? <FilterTMS /> : <FilterOMS />}</div>
      <div className={styles.main}>
        <div className={styles.main_header}>
          <div className={styles.main_header_left}>
            <Segmented<number>
              options={[
                { label: '全部', value: -1 },
                ...getLogisticsStatusName.valueList.map(v => ({ label: getLogisticsStatusName(v), value: v })),
              ]}
              value={logisticsStatus ?? -1}
              onChange={v => {
                setReqData({ logisticsStatus: v === -1 ? undefined : v, page: 1 })
                getData(true)
              }}
            />
          </div>
          {$APP === 'TMS' && (
            <Space className={styles.main_header_right} size={4}>
              <Button
                type="primary"
                disabled={!selectedLen}
                onClick={async () => {
                  const list = selectWaybillNos.filter(
                    item =>
                      (data?.records || []).findIndex(
                        recordItem => item === recordItem.waybillNo && !recordItem.createShippingOrderStatus,
                      ) > -1,
                  )
                  const result = await aptPostCreateShippingOrders({ waybillNos: list })
                  if (result.failedWaybillMesses.length <= 0) {
                    message.success(`创建物流订单成功，成功${result.succeedWaybillNos.length}条,请去牛迈系统发布轨迹`)
                  } else {
                    message.warning({
                      content: (
                        <>
                          <div>
                            创建完成，成功{result.succeedWaybillNos.length}条,失败
                            {result.failedWaybillMesses.length}条
                          </div>
                          <div>
                            失败原因
                            {result.failedWaybillMesses.map(item => (
                              <div key={item.waybillNo}>{item.message}</div>
                            ))}
                          </div>
                        </>
                      ),
                      duration: 3,
                    })
                  }

                  getData()
                }}
              >
                批量创建物流订单
              </Button>
              {/* <Button type="primary" disabled={!selectedLen}>
                批量留言
              </Button> */}
              <Button
                type="primary"
                onClick={() => {
                  const modalUpdate = popupSlot.insert(<UploadPODFilesModal destroy={() => modalUpdate(null)} />)
                }}
              >
                上传POD附件
              </Button>
              <Button
                type="primary"
                onClick={() => {
                  const modalUpdate = popupSlot.insert(
                    <InpTransferOrderNumModal
                      destroy={() => modalUpdate(null)}
                      onSuccess={() => getData() /* 无需回到第一页 */}
                    />,
                  )
                }}
              >
                录入转单号
              </Button>
            </Space>
          )}
        </div>
        <div className={styles.main_body}>
          <CusAgGrid<IOrderListItem>
            ref={gridRef}
            loading={loading}
            rowData={data?.records}
            defaultColDef={defaultColDef}
            columnDefs={columnDefs}
            rowSelection={rowSelection}
            onRowSelected={onRowSelected}
            statusBar={statusBar}
            sideBar={sideBar}
            onColumnVisible={onColumnVisible}
            onGridReady={onGridReady}
            onColumnGroupOpened={onColumnGroupOpened}
          />
        </div>
      </div>
      <popupSlot.Slot />
    </div>
  )
}
